<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <!-- card 的头部 -->
    <template #header>
      <div>
        <span>
          <el-button
            type="primary"
            size="default"
            :icon="Plus"
            @click="handleAddTardemark"
            v-has="'btn.Trademark.add'"
            >添加</el-button
          >
        </span>
      </div>
    </template>
    <!-- card body -->
    <el-table class="table" :data="trademarkListData" border stripe>
      <el-table-column type="index" width="88" align="center" label="序号" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="Logo">
        <!-- 
          作用域插槽：数据在 el-table :data="trademarkListData" 的时候已经传入了 el-table-column 使用作用域插槽子传父 
          一般在表格中，一定有方法获取当前一行的完整的数据
        -->
        <template #default="{ row }">
          <el-image
            class="image"
            :src="row.logoUrl"
            fit="cover"
            loading="lazy"
            :key="row.id"
          >
            <template #placeholder>
              <div class="image-slot">Loading<span class="dot">...</span></div>
            </template>
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="default"
            :icon="Edit"
            @click="handleUpdataTardemark(row)"
            v-has="'btn.Trademark.update'"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="default"
            :icon="Delete"
            @click="handleDeleteTardemark(row)"
            v-has="'btn.Trademark.remove'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="limit"
      :pager-count="successivePage"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      :page-sizes="pageSizes"
    />

    <!-- 新增&删除 弹窗 -->
    <el-dialog
      custom-class="dialog"
      v-model="dialogFormVisible"
      :title="form.id ? '修改品牌' : '新增品牌'"
      draggable
    >
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="tmName"
        >
          <el-input
            v-model="form.tmName"
            autocomplete="off"
            @keydown.enter.prevent=""
          />
        </el-form-item>
        <el-form-item label="LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseURL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">上传图片必须是jpg 并且不能大于2M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, watch } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Delete, Edit, Plus, Picture } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

import type {
  RequestTrademarkListReturnRecordsType,
  RequestUpdataTardemarkParamsType,
} from "@/api/product/interface";

import {
  requestTardemarkList,
  requestUpdateTardemark,
  requestAddTardemark,
  requestDeleteTardemark,
} from "@/api/product";

/* 品牌列表 */
// 品牌表格数据
const trademarkListData = ref<RequestTrademarkListReturnRecordsType>([]);
// 获取品牌表格数据方法
const getTrademarkListData = async () => {
  try {
    const result = await requestTardemarkList({
      page: page.value,
      limit: limit.value,
    });
    trademarkListData.value = result.records;
    total.value = result.total;
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};
// 初始化的时候请求数据
onMounted(() => {
  // 初始请求：品牌表格数据
  getTrademarkListData();
});

/* 分页 */
// 分页数据
const paginationData = ref({
  page: 1,
  limit: 10,
  total: 0,
  successivePage: 5,
  pageSizes: [10, 20, 30],
});
const { page, limit, total, successivePage, pageSizes } = toRefs(
  paginationData.value
);
// 监听 page limit 的变化重新加载数据
watch([page, limit], () => {
  getTrademarkListData();
});

/* 新增&删除 弹窗 */
// 弹窗数据
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";
const form = reactive<RequestUpdataTardemarkParamsType>({
  id: 0,
  tmName: "",
  logoUrl: "",
});
// 本地上传图片地址
const imageUrl = ref("");
// 图片上传路径(走代理)
const baseURL = import.meta.env.VITE_API_URL;
// 表单校验(全局：提交的时候)
const ruleFormRef = ref<FormInstance>();
// 表单单个校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "品牌名称必填", trigger: "blur" },
    { min: 2, max: 8, message: "品牌名称长度2-8", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "LOGO必须上传",
      trigger: "change", //无论写什么都可以,因为整体校验才会触发
    },
  ],
});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!); // 在本地生成图片
  form.logoUrl = response.data;
  ElMessage.success("图片上传成功！！！");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
// 修改按钮事件回调
const handleUpdataTardemark = (row: any) => {
  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  // 打开弹窗
  dialogFormVisible.value = true;
  // 数据回填
  form.id = row.id;
  form.tmName = row.tmName;
  form.logoUrl = row.logoUrl;
  imageUrl.value = row.logoUrl;
};
// 添加按钮事件回调
const handleAddTardemark = () => {
  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  // 打开弹窗
  dialogFormVisible.value = true;
  // 清空修改按钮的回填数据
  form.id = 0;
  form.tmName = "";
  form.logoUrl = "";
  imageUrl.value = "";
};
// 确认按钮事件回调
const handleConfirm = async () => {
  // 数据校验
  try {
    await ruleFormRef.value?.validate();
  } catch (e) {
    return ElMessage.error("校验失败！！！");
  }
  // 关闭弹窗
  dialogFormVisible.value = false;
  // 判断是新增还是删除(通过数据的 id 来判断)
  if (form.id) {
    // 有 id 就是修改
    try {
      await requestUpdateTardemark(form);
      // 重新加载数据
      getTrademarkListData();
      ElMessage.success("修改成功");
    } catch (error) {
      ElMessage.error("修改失败");
    }
  } else {
    // 没有 id 就是新增
    try {
      await requestAddTardemark(form);
      // 重新加载数据
      getTrademarkListData();
      // 将当前页定位到第一页
      paginationData.value.page = 1;
      ElMessage.success("新增成功");
    } catch (error) {
      ElMessage.error("新增失败");
    }
  }
};
// 删除按钮事件回调
const handleDeleteTardemark = (row: any) => {
  ElMessageBox.confirm("你确认要删除吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(async () => {
      // 发送删除请求
      try {
        await requestDeleteTardemark(row.id);
        // 重新加载数据
        getTrademarkListData();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      } catch (error) {
        ElMessage({
          type: "error",
          message: "删除失败",
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    });
};
</script>

<style>
.dialog {
  margin: 100px auto;
}

/* 上传图片 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.image {
  min-width: 100px;
  height: 100px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 50px;
}

.table {
  margin-bottom: 30px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
